#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->treeWidget->setHeaderLabel("动物");
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0, "cat");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0, "doy");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item3->setText(0, "sheep");
    ui->treeWidget->addTopLevelItem(item3);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    const QString& text = ui->lineEdit->text();

    if(text.isEmpty())
    {
        return;
    }
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, text);
    ui->treeWidget->addTopLevelItem(item);
}


void Widget::on_pushButton_2_clicked()
{
    //获取输入框文本
    const QString& text = ui->lineEdit->text();
    if(text.isEmpty())
    {
        return;
    }
    //找到父亲节点
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    if(currentItem == nullptr)
    {
        return;
    }
    //新生成一个QTreeWidgetItem
    QTreeWidgetItem* newItem = new QTreeWidgetItem();
    //设置文本，添加至父节点中，展开父节点
    newItem->setText(0, text);
    currentItem->addChild(newItem);
    currentItem->setExpanded(true);

}


void Widget::on_pushButton_3_clicked()
{
    //获取当前选中的节点
    QTreeWidgetItem* currentItem = ui->treeWidget->currentItem();
    //为空则没有选中，返回
    if(currentItem == nullptr){
        return;
    }
    //获取当前选中节点的父亲节点
    QTreeWidgetItem* Parent = currentItem->parent();
    //为空则该节点为顶层节点
    if(Parent == nullptr){
        //获取顶层节点的下标
        int index = ui->treeWidget->indexOfTopLevelItem(currentItem);
        //删除顶层节点
        ui->treeWidget->takeTopLevelItem(index);
    }else{
        //删除非顶层节点
        Parent->removeChild(currentItem);
    }
}

